/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.cem.cemweb.util;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;

import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
/**
 *
 * @author soloink
 */
public class HibernateFactory {
    private static SessionFactory sessionFactory;
    private static Log log= LogFactory.getLog(HibernateFactory.class);
    
    public static SessionFactory buildSessionFactory() throws HibernateException{
        if(sessionFactory != null){
            closeFactory();
        }
        
        Configuration configuration = new Configuration();
        configuration.configure();
        sessionFactory = configuration.buildSessionFactory();
        return sessionFactory;
    }
    
    public static SessionFactory getSessionFactory(){
        return sessionFactory;
    }
    
    public static Session openSession() throws HibernateException{
        return sessionFactory.openSession();
    }
    
    public static void closeFactory(){
        if(sessionFactory != null){
            try{
                sessionFactory.close();
            }catch(HibernateException ignored){
                log.error("HibernateFactory:closeFactory: Unable to close sessionFactory",ignored);
            }
        }
    }
    
    public static void close(Session session){
        if(session != null){
            try{
                session.close();
            }catch(HibernateException ignored){
                log.error("HibernateFactory:close: Unable to close session",ignored);
            }
        }
    }
    
    public static void rollback(Transaction tx){
        try{
            if(tx != null){ tx.rollback();}
        }catch(HibernateException ignored){
            log.error("HibernateFactory:rollback: Unable to rollback transaction",ignored);
        }
    }
}
